﻿using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Menu;
using Application = Autodesk.Revit.ApplicationServices.Application;

namespace RevitAddin
{
    [TransactionAttribute(TransactionMode.Manual)]
    [RegenerationAttribute(RegenerationOption.Manual)]
    public class TFCodeCMD : IExternalEventHandler
    {
        public bool isTCode { get; set; }
        public int myCount { get; set; }
       
        public void Execute(UIApplication app)
        {
            UIDocument uidoc = app.ActiveUIDocument;
            Document doc = uidoc.Document;
            Application revitApp = app.Application;
            string myCode = "T";
            if (isTCode)
            {
                myCode = "T";
            }
            else {
                myCode = "F";
            }
            try
            {
               

                List<Reference> referList= new List<Reference>();
                int count = 0;
                while (count< myCount)
                {
                   Reference refer= uidoc.Selection.PickObject(ObjectType.Element, new ConnSelectionFilter(), "请按照顺序选择多个连接件");
                    referList.Add(refer);

                    count++;
                }
         
                List<ConnectorElement> connectorList = referList.ConvertAll(e => doc.GetElement(e) as ConnectorElement);
                int scode = 0;
                if (connectorList.Count > 0) 
                {
                    Transaction ts = new Transaction(doc, Guid.NewGuid().ToString().Substring(0, 10));
                    ts.Start();
                    for (int i = 0; i < connectorList.Count; i++)
                    {
                        Parameter para= connectorList[i].LookupParameter("连接件说明");
                        if (para != null) {
                            para.Set(myCode+"-" + (scode + 1));
                        }
                        scode++;
                    }

                    ts.Commit();
                       
                }



               
            }
            catch (Exception ex)
            {
                TaskDialog.Show("温馨提示1", "\n" + ex.Message + ex.StackTrace);
            }
        }

        public string GetName()
        {
            return "TFCodeCMD";
        }
    }
    public class ConnSelectionFilter : ISelectionFilter

    {
        public bool AllowElement(Element elem)
        {
            if (elem.Category.Name == "连接件图元")

            {

                return true;

            }

            return false;
        }

        public bool AllowReference(Reference reference, Autodesk.Revit.DB.XYZ position)
        {
            throw new NotImplementedException();
        }

       



      
    }
}
